#include "qt_preinclude.h"
#include "websocketserver.h"

    WebSocketServer::WebSocketServer(quint16 port, QObject *parent = nullptr)
        : QObject(parent), m_port(port)
    {
        qDebug() << "SIZE_MAX = " << SIZE_MAX ;
        qDebug() << "_HAS_STD_BYTE = " << _HAS_STD_BYTE ;

        m_server = new QWebSocketServer("Echo Server", QWebSocketServer::NonSecureMode, this);
        connect(m_server, &QWebSocketServer::newConnection, this, &WebSocketServer::onNewConnection);

        if (m_server->listen(QHostAddress::Any, m_port)) {
            qDebug() << "WebSocket server started on port" << m_port;
        } else {
            qDebug() << "Failed to start WebSocket server.";
        }
    }


    void WebSocketServer::onNewConnection()
    {
        QWebSocket *clientSocket = m_server->nextPendingConnection();
        connect(clientSocket, &QWebSocket::textMessageReceived, this, &WebSocketServer::onTextMessageReceived);
        connect(clientSocket, &QWebSocket::disconnected, this, &WebSocketServer::onSocketDisconnected);
        qDebug() << "New client connected:" << clientSocket->peerAddress().toString();
    }

    void WebSocketServer::onTextMessageReceived(const QString &message)
    {
        QWebSocket *clientSocket = qobject_cast<QWebSocket *>(sender());
        if (clientSocket) {
            qDebug() << "Received message:" << message;
            clientSocket->sendTextMessage("Echo: " + message);
        }
    }

    void WebSocketServer::onSocketDisconnected()
    {
        QWebSocket *clientSocket = qobject_cast<QWebSocket *>(sender());
        if (clientSocket) {
            qDebug() << "Client disconnected:" << clientSocket->peerAddress().toString();
            clientSocket->deleteLater();
        }
    }
